import React from 'react';
import './index.css'
// 左边 边界
// import ruleWin from '../../../node-game/webcocket/ruleWin.js'
import { Modal, Button, WhiteSpace, WingBlank, Toast } from 'antd-mobile';
import writeImg from '../assets/images/write.png';
import blackImg from '../assets/images/black.png';
import defultImg from '../assets/images/defult.png';
const alert = Modal.alert;


const ws = new WebSocket('ws://192.168.44.254:8887')
//  const ws = new WebSocket('ws://localhost:8887')

// 监听这个连接
ws.onopen = () => {
    console.log('连接成功')
}


// 监听服务端发来的消息


// 点击发送消息
//  ws.send(val)

// 监听服务端的断开
ws.onclose = () => {
    console.log('服务关闭了')
}
export default class Game extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            nextPlay: "black",
            chessboard: new Array(225).fill(null),
            id: "",
            ip: "",
            status: "",
            nextPlayId: "",
            canPlay: false,
            isReady:false,
            clients:[]
        }
    }
    init = () => {
        ws.send(JSON.stringify({
            status: this.state.status,
            type: "again",
            id: this.state.id
        }))
        Toast.info("请等待对手同意"); 
    }
    onLister = () => {


        ws.onmessage = (msg) => {
            const res = JSON.parse(msg.data)
            const { playState, ip, id, status, nextPlay, nextPlayId, winner, index,clients,data } = res
            switch (playState) {
                case 1:
                    this.setState({
                        playState,
                        id,
                        ip,
                        nextPlay,
                        status,
                        nextPlayId
                    })
                   
                    this.onlyOne()
                    break;
                case 2:
                    this.setState({
                        playState,
                        canPlay: true,
                        nextPlayId,
                        nextPlay,
                        chessboard: new Array(225).fill(null)
                    })
                    this.allReady()
                    break;
                case 3:
                    if (winner) {
                        alert(`恭喜${winner}胜利`)
                    }
                    let arr = JSON.parse(JSON.stringify(this.state.chessboard));
                    arr[index] = status;
                    this.setState({
                        chessboard: arr,
                        playState,
                        canPlay: true,
                        nextPlayId,
                        nextPlay
                    })
                    break;
                case 4:
                    alert(`${status}退出了`)
                    this.setState({
                        chessboard: new Array(225).fill(null),
                        canPlay: false,
                        nextPlayId,
                        nextPlay
                    })
                    break;
                case 5:
                    this.againPlay(data);
                    break;
                case 6:
                    alert(`你得请求已被拒绝`)
                    break;
                case 7:
                    console.log("准备了")
                    this.setState({
                        isReady:clients.find(item=>item.id==this.state.id).isReady,
                        clients
                    })
                    break;
            }
            
            // playState:1,  //游戏是否开始
            // ip,  //用户ip
            // id, //用户id
            // status, //用户棋色
            // nextPlay, //下一步走棋棋色
            // nextPlayId, //下一步走棋的用户id
            // client
        }
    }
    againPlay = (data) => {
        const okBack = () => {
            ws.send(JSON.stringify({
                playState: 5,
                type: "againOk",
                id: this.state.id
            }))
        }
        const cancelBack = () => {
            ws.send(JSON.stringify({
                playState: 5,
                type: "againNo",
                id: this.state.id
            }))
        }
        alert(`${data.status}请求再来一次`, "", [{ text: "拒绝", onPress: cancelBack }, { text: "同意", onPress: okBack }])
    }
    onlyOne = () => {
        Toast.info('当前没有对手,请稍等', 3);
    }
    allReady = () => {
        Toast.info('现在开始', 3);
    }
    componentDidMount() {
        this.onLister()
    }
    componentWillUnmount() {

    }

    palyChess = (index) => {
        if (!this.state.canPlay) return

        const { chessboard, nextPlay, nextPlayId, id, status } = this.state
        if (nextPlayId != id) {
            Toast.info(`当前为${nextPlay}走棋`)
            return false
        }

        if (chessboard[index]) return false
        const array = chessboard
        array[index] = nextPlay == "white" ? "white" : "black"
        // this.checkWinner(index)
        this.setState({
            nextPlay: nextPlay == "white" ? "black" : "white",
            chessboard: array,
            canPlay: false
        })
        ws.send(JSON.stringify({
            index,
            id,
            status
        }))
    }
    clickReady=()=>{
        ws.send(JSON.stringify({
            type:"ready", //用户准备
            id:this.state.id,
            isReady:true
        }))
    }
    // onClose = key => () => {
    //     this.setState({
    //       [key]: false,
    //     });
    //   }
    // checkWinner(index) {
    //     const { chessboard } = this.state
    //     if (ruleWin(chessboard, index)) {
    //         alert(chessboard[index] + " win!!!")
    //     }

    // }
    render() {
        return (
            <div>
                <div className="nowPlayer">当前玩家:{this.state.nextPlay}</div>
                <div className="contnet">
                    <div className="player1 player">
                        <img src={writeImg} alt="" />
                        <div style={{marginTop:"10px"}} className="address">{this.state.ip}</div>
                        <Button onClick={this.clickReady} disabled={this.state.isReady}>{this.state.isReady?"已准备":"准备"}</Button>
                    </div>
                    <div className="checkerboard">
                        {this.state.chessboard.map((item, index) => {
                            return <div className="cell" key={index}>
                                <div className={`piece ${item}`} onClick={() => this.palyChess(index)}></div>
                            </div>
                        })}
                        <Button className="startGame" onClick={this.init}>再来一次</Button>
                    </div>
                    <div className="player2 player">
                        <img src={blackImg} alt="" />
                        <div className="address">432</div>
                        <Button disabled>准备</Button>
                    </div>
                </div>
                
                {/* <Modal
                    visible={this.state.modal1}
                    transparent
                    maskClosable={false}
                    onClose={this.onClose('modal1')}
                    footer={[{ text: 'Ok', onPress: () => { console.log('ok'); this.onClose('modal1')(); } }]}
                    wrapProps={{ onTouchStart: this.onWrapTouchStart }}
                    afterClose={() => { alert('afterClose'); }}
                >
                    <div style={{ height: 100, overflow: 'scroll' }}>
                       啊啊啊啊啊
                    </div>
                </Modal> */}

            </div>

        )
    }
}